import React, { useState } from 'react';
import {
  Box,
  Typography,
  TextField,
  Button,
  Paper,
  Alert,
  Snackbar,
  Grid,
  CircularProgress,
  useTheme,
  alpha,
  Fade,
  IconButton,
  Tooltip,
} from '@mui/material';
import EditIcon from '@mui/icons-material/Edit';
import CloseIcon from '@mui/icons-material/Close';
import DescriptionIcon from '@mui/icons-material/Description';
import FileDownloadIcon from '@mui/icons-material/FileDownload';

interface ResumeProps {
  user: any;
  onUpdate: () => void;
}

const Resume: React.FC<ResumeProps> = ({ user, onUpdate }) => {
  const theme = useTheme();
  const [editMode, setEditMode] = useState(false);
  const [formData, setFormData] = useState({
    resume_title: user.resume_title || '',
    resume_description: user.resume_description || '',
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState(false);
  const [successMessage, setSuccessMessage] = useState('');

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError('');

    try {
      const token = localStorage.getItem('token');
      if (!token) {
        throw new Error('未登录，请先登录');
      }

      // 更新个人综述信息
      const updateData = {
        resume_title: formData.resume_title,
        resume_description: formData.resume_description
      };

      const response = await fetch('/api/profile', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify(updateData)
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || '更新个人综述失败');
      }

      // 更新本地存储的用户信息
      const currentUser = JSON.parse(localStorage.getItem('userData') || '{}');
      const updatedUser = { ...currentUser, ...updateData };
      localStorage.setItem('userData', JSON.stringify(updatedUser));

      // 调用父组件的更新方法
      onUpdate();

      setSuccessMessage('个人综述更新成功');
      setSuccess(true);
      setEditMode(false);
    } catch (err) {
      setError((err as Error).message);
    } finally {
      setLoading(false);
    }
  };

  const handleCancel = () => {
    // 重置表单数据为用户原始数据
    setFormData({
      resume_title: user.resume_title || '',
      resume_description: user.resume_description || '',
    });
    setEditMode(false);
    setError('');
  };

  const handleExportResume = async () => {
    setLoading(true);
    setError('');

    try {
      // 获取用户信息
      const userJson = localStorage.getItem('user');
      if (!userJson) {
        throw new Error('未登录，请先登录');
      }

      // 解析用户信息
      let userId;
      try {
        const userObj = JSON.parse(userJson);
        userId = userObj.id;
        if (!userId) {
          throw new Error('用户信息不完整');
        }
      } catch (e) {
        console.error('解析用户信息错误:', e);
        throw new Error('用户信息无效，请重新登录');
      }

      // 使用完整版API，直接传递用户ID
      console.log('发送请求到 /api/resume/export-full');
      console.log('用户ID:', userId);

      // 显示加载中提示
      setSuccessMessage('正在生成简历，请稍候...');
      setSuccess(true);

      // 直接在新窗口打开下载链接
      window.open(`/api/resume/export-full?userId=${userId}`, '_blank');

      setSuccessMessage('简历导出成功');
      setSuccess(true);
    } catch (err) {
      setError((err as Error).message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Box sx={{ py: 2, px: { xs: 2, md: 3 } }}>
      <Snackbar
        open={success}
        autoHideDuration={3000}
        onClose={() => setSuccess(false)}
        anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
      >
        <Alert
          severity="success"
          onClose={() => setSuccess(false)}
          sx={{
            borderRadius: '12px',
            boxShadow: '0 8px 16px rgba(0, 0, 0, 0.1)',
            '& .MuiAlert-icon': {
              alignItems: 'center',
            }
          }}
        >
          {successMessage}
        </Alert>
      </Snackbar>

      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
        <Typography
          variant="h5"
          component="h2"
          sx={{
            fontSize: '1.5rem',
            fontWeight: 600,
            color: theme.palette.text.primary,
          }}
        >
          个人综述
        </Typography>
        <Box sx={{ display: 'flex', gap: 2 }}>
          <Tooltip title="导出简历">
            <span> {/* 包装元素以支持禁用状态下的Tooltip */}
              <Button
                startIcon={loading ? <CircularProgress size={20} /> : <FileDownloadIcon />}
                variant="outlined"
                color="primary"
                onClick={handleExportResume}
                disabled={loading}
                sx={{
                  borderRadius: '24px',
                  px: 3,
                  py: 1,
                  fontWeight: 500,
                  transition: 'all 0.2s',
                  '&:hover': {
                    boxShadow: '0 4px 12px rgba(25, 118, 210, 0.2)',
                  },
                }}
              >
                {loading ? '导出中...' : '导出简历'}
              </Button>
            </span>
          </Tooltip>
          <Button
            startIcon={<EditIcon />}
            variant={editMode ? "contained" : "outlined"}
            color={editMode ? "primary" : "secondary"}
            onClick={() => setEditMode(!editMode)}
            sx={{
              borderRadius: '24px',
              px: 3,
              py: 1,
              fontWeight: 500,
              transition: 'all 0.2s',
              ...(editMode && {
                boxShadow: '0 4px 12px rgba(25, 118, 210, 0.2)',
                '&:hover': {
                  boxShadow: '0 6px 16px rgba(25, 118, 210, 0.3)',
                },
              })
            }}
          >
            {editMode ? '正在编辑' : '编辑综述'}
          </Button>
        </Box>
      </Box>

      {error && (
        <Alert
          severity="error"
          sx={{
            mb: 3,
            borderRadius: '12px',
            '& .MuiAlert-icon': {
              alignItems: 'center',
            }
          }}
        >
          {error}
        </Alert>
      )}

      <Fade in={true} timeout={800}>
        {editMode ? (
          <Paper
            elevation={0}
            sx={{
              p: 3,
              borderRadius: '16px',
              backgroundColor: alpha('#fff', 0.9),
              backdropFilter: 'blur(10px)',
              boxShadow: '0 4px 30px rgba(0, 0, 0, 0.05)',
              border: `1px solid ${alpha(theme.palette.divider, 0.1)}`,
            }}
          >
            <form onSubmit={handleSubmit}>
              <Grid container spacing={3}>
                <Grid item xs={12}>
                  <TextField
                    fullWidth
                    label="综述标题"
                    name="resume_title"
                    value={formData.resume_title}
                    onChange={handleChange}
                    placeholder="例如: 前端开发工程师求职意向"
                    required
                    variant="outlined"
                    InputProps={{
                      sx: {
                        borderRadius: '12px',
                      }
                    }}
                  />
                </Grid>
                <Grid item xs={12}>
                  <TextField
                    fullWidth
                    label="个人综述"
                    name="resume_description"
                    value={formData.resume_description}
                    onChange={handleChange}
                    multiline
                    rows={8}
                    placeholder="请在此处写入您的个人综述，包括您的职业目标、专业技能、过往经历亮点等综合信息。这部分内容将作为您个人介绍的核心内容展示给访问者。"
                    required
                    variant="outlined"
                    InputProps={{
                      sx: {
                        borderRadius: '12px',
                      }
                    }}
                  />
                </Grid>
                <Grid item xs={12} sx={{ textAlign: 'right', mt: 2 }}>
                  <Button
                    variant="outlined"
                    color="secondary"
                    onClick={handleCancel}
                    sx={{
                      mr: 2,
                      borderRadius: '10px',
                      px: 3,
                      fontWeight: 500,
                    }}
                    startIcon={<CloseIcon />}
                  >
                    取消
                  </Button>
                  <Button
                    type="submit"
                    variant="contained"
                    color="primary"
                    disabled={loading}
                    sx={{
                      borderRadius: '10px',
                      px: 3,
                      fontWeight: 500,
                      boxShadow: '0 4px 12px rgba(25, 118, 210, 0.2)',
                      '&:hover': {
                        boxShadow: '0 6px 16px rgba(25, 118, 210, 0.3)',
                        transform: 'translateY(-2px)',
                      },
                    }}
                  >
                    {loading ? (
                      <>
                        <CircularProgress size={24} sx={{ mr: 1 }} />
                        保存中...
                      </>
                    ) : '保存综述'}
                  </Button>
                </Grid>
              </Grid>
            </form>
          </Paper>
        ) : (
          <Paper
            elevation={0}
            sx={{
              p: 3,
              borderRadius: '16px',
              backgroundColor: alpha('#fff', 0.9),
              backdropFilter: 'blur(10px)',
              boxShadow: '0 4px 30px rgba(0, 0, 0, 0.05)',
              border: `1px solid ${alpha(theme.palette.divider, 0.1)}`,
              position: 'relative',
              overflow: 'hidden',
              transition: 'all 0.3s ease',
              '&:hover': {
                boxShadow: '0 8px 30px rgba(0, 0, 0, 0.08)',
              },
            }}
          >
            {user.resume_title || user.resume_description ? (
              <Box>
                {user.resume_title && (
                  <Typography
                    variant="h6"
                    gutterBottom
                    sx={{
                      fontWeight: 600,
                      color: theme.palette.text.primary,
                      fontSize: '1.25rem',
                      mb: 2,
                      display: 'flex',
                      alignItems: 'center',
                    }}
                  >
                    <DescriptionIcon
                      sx={{
                        mr: 1,
                        color: theme.palette.primary.main
                      }}
                    />
                    {user.resume_title}
                  </Typography>
                )}

                {user.resume_description ? (
                  <Typography
                    variant="body1"
                    sx={{
                      whiteSpace: 'pre-line',
                      mt: 2,
                      color: theme.palette.text.primary,
                      lineHeight: 1.7,
                      fontSize: '1rem',
                      letterSpacing: '0.01em',
                    }}
                  >
                    {user.resume_description}
                  </Typography>
                ) : (
                  <Typography
                    variant="body1"
                    sx={{
                      color: theme.palette.text.secondary,
                      fontSize: '1rem',
                    }}
                  >
                    您还没有填写个人综述内容，点击"编辑综述"按钮添加
                  </Typography>
                )}

                <IconButton
                  onClick={() => setEditMode(true)}
                  sx={{
                    position: 'absolute',
                    top: 16,
                    right: 16,
                    backgroundColor: alpha(theme.palette.primary.main, 0.08),
                    '&:hover': {
                      backgroundColor: alpha(theme.palette.primary.main, 0.12),
                    },
                  }}
                >
                  <EditIcon fontSize="small" />
                </IconButton>
              </Box>
            ) : (
              <Box sx={{ textAlign: 'center', py: 6, px: 3 }}>
                <DescriptionIcon
                  sx={{
                    fontSize: 56,
                    color: alpha(theme.palette.primary.main, 0.6),
                    mb: 2,
                  }}
                />
                <Typography
                  variant="body1"
                  sx={{
                    color: theme.palette.text.secondary,
                    fontSize: '1rem',
                    mb: 3,
                  }}
                >
                  您还没有填写个人综述，点击"编辑综述"按钮开始添加
                </Typography>
                <Button
                  variant="contained"
                  color="primary"
                  startIcon={<EditIcon />}
                  onClick={() => setEditMode(true)}
                  sx={{
                    borderRadius: '24px',
                    px: 3,
                    py: 1,
                    fontWeight: 500,
                    boxShadow: '0 4px 12px rgba(25, 118, 210, 0.2)',
                    '&:hover': {
                      boxShadow: '0 6px 16px rgba(25, 118, 210, 0.3)',
                      transform: 'translateY(-2px)',
                    },
                  }}
                >
                  立即添加综述
                </Button>
              </Box>
            )}
          </Paper>
        )}
      </Fade>
    </Box>
  );
};

export default Resume;